<template>
    <div class="app-container">
        <div class="searchAll" slot="search">
            <el-form :model="queryParams" ref="queryForm" label-position="right" v-show="showSearch" label-width="68px">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item :label="$t('postManage.postCode')" prop="postCode">
                            <el-input v-model="queryParams.postCode" :placeholder="$t('public.placeholder',{placeholder:$t('postManage.postCode')})" clearable size="small" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('postManage.postName')" prop="postName">
                            <el-input v-model="queryParams.postName" :placeholder="$t('public.placeholder',{placeholder:$t('postManage.postName')})" clearable size="small" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('public.status')" prop="status">
                            <el-select v-model="queryParams.status" style="wdith:100%;" :placeholder="$t('public.select_holder',{select_holder: $t('postManage.postStatus')})" clearable size="small">
                                <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <div class="searchAres searchAresHeng">
                            <el-button type="primary" icon="el-icon-search" size="mini" class="searchBtn" @click="handleQuery">{{ $t("public.query") }}</el-button>
                            <el-button class="resectBtn" icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("public.reset") }}</el-button>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="tableList">
            <div class="insTitle">
                <span>{{ $t("systemTitle.postManagement") }}</span>
            </div>
            <div class="btnGroup">
                <el-button v-hasPermi="['tenant:post:add']" type="primary" icon="el-icon-plus" size="mini" class="additemBtn" @click="handleAdd">{{ $t("public.add") }}</el-button>
                <el-button v-hasPermi="['tenant:post:remove']" icon="el-icon-delete" size="mini" class="deleteitemBtn" :disabled="multiple" @click="handleDelete">{{ $t("public.delete") }}</el-button>
                <el-button v-hasPermi="['tenant:post:export']" class="exportitemBtn" size="mini" :loading="exportLoading" @click="handleExport"><img src="../../../assets/images/icons/daochu.png" alt=""> {{ $t("public.export") }}</el-button>

            </div>
            <el-table stripe v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />

                <el-table-column :label="$t('postManage.postNum')" align="center" prop="postId" />
                <el-table-column :label="$t('postManage.postCode')" align="center" prop="postCode" />
                <el-table-column :label="$t('postManage.postName')" align="center" prop="postName" />
                <el-table-column :label="$t('postManage.postSort')" align="center" prop="postSort" />

                <el-table-column :label="$t('public.createTime')" align="center" prop="createTime" width="180">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column :label="$t('public.status')" align="center" fixed="right" prop="status" width="100">
                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
                    </template>
                </el-table-column>
                <el-table-column :label="$t('public.opera')" fixed="right" align="center" min-width="100">
                    <template slot-scope="scope">
                        <div class="action-wrap">
                            <table-body-btn type="gwedit" :name="$t('public.edit')" @click.native="handleUpdate(scope.row)" v-hasPermi="['tenant:post:edit']" />
                            <table-body-btn type="gwdelete" :name="$t('public.delete')" @click.native="handleDelete(scope.row)" v-hasPermi="['tenant:post:remove']" />
                            <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['tenant:role:edit']">
                                <span class="el-dropdown-link">
                                    <table-body-btn type="more" />
                                </span>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item command="handleDataScope" icon="el-icon-circle-check" v-hasPermi="['tenant:role:edit']">{{$t('roleManage.dataAuthority')}}</el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" layout="total, sizes, prev, pager, next, jumper" />
        </div>

        <!-- 添加或修改岗位对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :fullscreen="fullscreen" :close-on-click-modal="false">
            <DialogTit slot="title" :title="title" :fullscreen.sync="fullscreen"></DialogTit>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-form-item :label="$t('postManage.postName')" prop="postName" size="small">
                    <el-input v-model="form.postName" :placeholder="$t('public.placeholder',{placeholder:$t('postManage.postName')})" />
                </el-form-item>
                <el-form-item :label="$t('postManage.postCode')" prop="postCode" size="small">
                    <el-input v-model="form.postCode" :placeholder="$t('public.placeholder',{placeholder:$t('postManage.postCode')})" />
                </el-form-item>
                <el-form-item :label="$t('postManage.postOrder')" prop="postSort" size="small">
                    <el-input-number v-model="form.postSort" controls-position="right" :min="0" step-strictly />
                </el-form-item>
                <el-form-item :label="$t('postManage.postStatus')" prop="status" size="small">
                    <el-radio-group v-model="form.status">
                        <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{dict.label}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item :label="$t('public.remark')" prop="remark" size="small">
                    <el-input v-model="form.remark" type="textarea" :placeholder="$t('public.placeholder',{placeholder:$t('public.remark')})" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel" size="small" icon="el-icon-close">{{$t('public.cancel')}}</el-button>
                <el-button type="primary" @click="submitForm" size="small" icon="el-icon-check">{{$t('public.define')}}</el-button>
            </div>
        </el-dialog>
        <!-- 分配角色数据权限对话框 -->
        <el-dialog :title="title" :visible.sync="openDataScope" width="500px" append-to-body :fullscreen="fullscreen2">
            <DialogTit slot="title" :title="title" :fullscreen.sync="fullscreen2"></DialogTit>
            <el-form :model="ruleForm" label-width="80px">
                <el-form-item label="岗位名称" size="small">
                    <el-input v-model="ruleForm.postName" :disabled="true" />
                </el-form-item>
                <el-form-item label="权限规则" size="small">
                    <el-select v-model="ruleForm.dataType" @change="dataScopeSelectChange" style="width:100%">
                        <el-option v-for="item in dataRules" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="权限范围" size="small">
                    <el-select v-model="ruleForm.dataScope" v-show="ruleForm.dataType==='1'" style="width:100%">
                        <el-option v-for="item in dataScopeOptions1" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                    <el-select v-model="ruleForm.dataScope" v-show="ruleForm.dataType==='2'" multiple filterable transfer style="width:100%">
                        <el-option v-for="item in dict.type.NYIQC_MATERIAL_MIDDLE" :key="item.value" :label="item.label" :value="item.label" />
                    </el-select>
                    <el-select v-model="ruleForm.dataScope" v-show="ruleForm.dataType==='3'" transfer style="width:100%">
                        <el-option v-for="item in dict.type.NYIQC_JOBS" :key="item.label" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelDataScope" icon="el-icon-close" size="small">{{ $t('public.cancel') }}</el-button>
                <el-button type="primary" @click="submitDataScope" icon="el-icon-check" size="small">{{ $t('public.define') }}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {addPost, delPost, getPost, getRule, listPost, saveRules, updatePost,} from '@/api/system/post'
import {getMasterialMaxMinData} from '@/api/basic/materialtype'

export default {
    name: 'Post',
    dicts: ['sys_normal_disable', 'NYIQC_JOBS','NYIQC_MATERIAL_MIDDLE'],
    data() {
        return {
            // 遮罩层
            loading: true,
            fullscreen2: false,
            // 导出遮罩层
            exportLoading: false,
            openDataScope: false,
            ruleForm: {
                dataScope: '',
                postName: null,
                dataType: '1',
            },
            dataRules: [
                {
                    value: '1',
                    label: '全部数据权限',
                },
                {
                    value: '2',
                    label: '物料中类',
                },
                // {
                //     value: '3',
                //     label: '物料编号',
                // },
            ],
            dataScopeOptions1: [
                {
                    value: '',
                    label: '空',
                },
            ],
            dataScopeOptions2: [],
            dataScopeOptions3: [
                {
                    value: '11',
                    label: '电芯',
                },
                {
                    value: '12',
                    label: '模组',
                },
            ],
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 岗位表格数据
            postList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 20,
                postCode: undefined,
                postName: undefined,
                status: undefined,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                postName: [
                    {
                        required: true,
                        message: '岗位名称不能为空',
                        trigger: 'blur',
                    },
                ],
                postCode: [
                    {
                        required: true,
                        message: '岗位编码不能为空',
                        trigger: 'blur',
                    },
                ],
                postSort: [
                    {
                        required: true,
                        message: '岗位顺序不能为空',
                        trigger: 'blur',
                    },
                ],
            },
            fullscreen: false,
            names: [],
        }
    },
    created() {
        this.getList()
        this.getMaterialType({ materialMax: 'all' }, 'materialMiddle')
    },
    methods: {
        dataScopeSelectChange() {
            if (this.ruleForm.dataType === '2') {
                this.ruleForm.dataScope = []
            } else {
                this.ruleForm.dataScope = null
            }
            this.$forceUpdate()
        },
        /** 提交按钮（数据权限） */
        submitDataScope: function () {
            if (this.ruleForm.postId != undefined) {
                let ruleForm = { ...this.ruleForm }
                if (ruleForm.dataType === '2') {
                    ruleForm.dataScope = ruleForm.dataScope.join(',')
                }

                saveRules(ruleForm).then((response) => {
                    this.$modal.msgSuccess(this.$t('formValidation.successfullyModified'))
                    this.openDataScope = false
                    this.getList()
                })
            }
        },
        // 取消按钮（数据权限）
        cancelDataScope() {
            this.openDataScope = false
            this.reset()
        },
        // 更多操作触发
        handleCommand(command, row) {
            switch (command) {
                case 'handleDataScope':
                    this.handleDataScope(row)
                    break
                case 'handleAuthUser':
                    this.handleAuthUser(row)
                    break
                default:
                    break
            }
        },
        getMaterialType(params, key) {
            getMasterialMaxMinData(params).then((res) => {
                this.dataScopeOptions2 = res.data
            })
        },

        /** 查询岗位列表 */
        getList() {
            this.loading = true
            listPost(this.queryParams).then((response) => {
                this.postList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        /** 分配数据权限操作 */
        handleDataScope(row) {
            this.reset()
            let ruleForm = {
                ...row,
                dataScope: '',
                dataType: '1',
            }
            // const roleDeptTreeselect = this.getRoleDeptTreeselect(row.roleId)
            getRule({ postId: row.postId }).then((response) => {
                if (response.data) {
                    ruleForm.dataType = response.data.dataType
                    ruleForm.dataScope = ruleForm.dataType==='2'?response.data.dataScope.split(','):response.data.dataScope
                }
                setTimeout(() => {
                    this.ruleForm = ruleForm
                }, 300)

                console.log(ruleForm)
                this.openDataScope = true
                this.title = '分配数据权限'
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                postId: undefined,
                postCode: undefined,
                postName: undefined,
                postSort: 0,
                status: '0',
                remark: undefined,
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.postId)
            this.names = selection.map((item) => item.postName)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = this.$t('postManage.addPost')
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const postId = row.postId || this.ids
            getPost(postId).then((response) => {
                this.form = response.data
                this.open = true
                this.title = this.$t('postManage.modPost')
            })
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (this.form.postId != undefined) {
                        updatePost(this.form).then((response) => {
                            this.$modal.msgSuccess(this.$t('formValidation.successfullyModified'))
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addPost(this.form).then((response) => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const postIds = (row && row.postId) || this.ids
            const names = (row && row.postName) || this.names
            console.log(names)
            this.$modal
                .confirm(`是否删除岗位名称为“${names}”的数据项？`)
                .then(function () {
                    return delPost(postIds)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess(this.$t('deptManage.delSuc'))
                })
                .catch(() => {})
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                'system/saas/post/export',
                {
                    ...this.queryParams,
                },
                `post_${new Date().getTime()}.xlsx`
            )
        },
    },
}
</script>
